/* Copyright Andy Mitchell 2007. No warranties */


function ComposeUI(gtdinboxPage){
	this._id = (new Date()).valueOf();
	this._eventObservers = new EventObservers(this);
	this._gtdinboxPage = gtdinboxPage;
	this._doc = gtdinboxPage.doc;
	this._labels = gtdinboxPage._labels;

	// Create the 'Compose Personal' button
	var elCompose = this._gtdinboxPage.gmailDOM.element("compose-mail");
	var elComposePersonal = elCompose.cloneNode(true);
	elComposePersonal.innerHTML = "Compose Personal";	// TODO language
	elCompose.parentNode.appendChild( this._doc.createElement("BR") );
	elCompose.parentNode.appendChild( elComposePersonal );
	this._eventObservers.observe(elCompose, "mousedown", this.clickCompose, false );
	this._eventObservers.observe(elComposePersonal, "mousedown", this.clickComposePersonal, false );
	
	this._tabs = [["compose-mail",elCompose.innerHTML], ["compose-personal",elComposePersonal.innerHTML]];
	
	this._labels.addEventHandler( this, "refresh-labels", this.labelsUpdate );
}

ComposeUI.prototype.viewChange = function(){
	this.refresh();
};

ComposeUI.prototype.labelsUpdate = function(){
	if( this._labelSelect ) this._labelSelect.refresh();
};

ComposeUI.prototype.refresh = function(attempt){
	// See if need to integrate into Compose page
try{
	
		// Retrieve compose table:
		var elTable = this._gtdinboxPage.gmailDOM.element("compose-table");
		if( elTable ){
			if( elTable.getAttribute("gtdComposing")=="1" ){
				if( !attempt ) attempt = 0;
				if( attempt<4 ) setTimeout( GIPROTOTYPE.bind(this, function(){this.refresh(++attempt)}), 500 );
				return;
			}
			
			elTable.setAttribute("gtdComposing", "1");
						
			// Create View Tabs
			var el = this._doc.createElement("DIV");
			var html = [];
			for( var i = 0; i < this._tabs.length; i++ ){
				html.push("<div id='" + this._id + this._tabs[i][0] + "' class='compose-tab' gtdComposeType='" + this._tabs[i][0] + "'>" + this._tabs[i][1] + "</div>");
			}
			el.innerHTML = html.join("");
			var elTr = this._createRow("compose", el);		
			this._eventObservers.observe( elTr, "mousedown", this.clickTab, false );
			
			var elTBody = elTable.getElementsByTagName("TBODY")[0];
			elTBody.insertBefore( elTr, elTBody.firstChild );
			
			// Add Labels Box
			if( this._labelSelect ){
			}else{
				this._labelSelect = new LabelSelectUI(this._gtdinboxPage, null, true);
				this._labelSelect.addEventHandler(this, "click-label", this.toggleLabel);
				
				this._showHiderLabels = new Showhider(this._gtdinboxPage, "compose-labels", {doc: this._doc, title:'Labels:', inline:true, elContent: this._labelSelect.el});	// TODO language
			}
			this._labelSelect.refresh();
			var elTr = this._createRow( "compose-labels", this._showHiderLabels.elContent, this._showHiderLabels.elTitle );
			var elTBody = elTable.getElementsByTagName("TBODY")[0];
			elTBody.appendChild( elTr );
		}
				
		
		if( this._doPersonal ){
			this._doPersonal = false;
			this.selectTab("compose-personal");
		}else if( !this._lastTab ){	// first run
			this.selectTab("compose-mail");
						
			if( this._toEmails ){
				var elTo = this._gtdinboxPage.gmailDOM.element("compose-to");
				elTo.value = this._toEmails;
				this._toEmails = null;
			}
		}
		
}catch(e){
	if( GTDDEBUGMODE ) alert("composeui viewChange\n" + e.toString());
}
};

ComposeUI.prototype._createRow = function(className, elContent, elTitle){
		var elTr = this._doc.createElement("TR");
			elTr.className = className;
		var elTd = this._doc.createElement("TD");
			elTd.className = "sXkcDf";
			elTd.style.position = "absolute";
			if( elTitle ) elTd.appendChild(elTitle);
		elTr.appendChild( elTd );
		var elTd = this._doc.createElement("TD");
			elTd.className = "J14TS";
			if( elContent ) elTd.appendChild(elContent);
		elTr.appendChild( elTd );
		var elTd = this._doc.createElement("TD");
			elTd.className = "MAd07b";
		elTr.appendChild( elTd );
		return elTr;
};

ComposeUI.prototype.clickCompose = function(event){
	if( this._labelSelect ) this._labelSelect.selected([]);
	this._lastTab = null;
	this._lastTo = null;
};
ComposeUI.prototype.clickComposePersonal = function(event){
	// Simulate click on Compose Message
	if( this._labelSelect ) this._labelSelect.selected([]);
	this._lastTab = null;
	this._lastTo = null;
	
	var elCompose = this._gtdinboxPage.gmailDOM.element("compose-mail");
	this._doPersonal = true;
	GIPROTOTYPE.doMouseEvent(this._doc, elCompose, "click");
};
ComposeUI.prototype.clickComposeTo = function(emails){
	if( this._labelSelect ) this._labelSelect.selected([]);
	this._lastTab = null;
	this._lastTo = null;
	this._doPersonal = false;
	
	this._toEmails = emails;
	var elCompose = this._gtdinboxPage.gmailDOM.element("compose-mail");
	GIPROTOTYPE.doMouseEvent(this._doc, elCompose, "click");
};

ComposeUI.prototype.clickTab = function(event, composeType){
	var el = GIPROTOTYPE.element(event);
	if( el.className.indexOf("compose-tab")==-1 ) return;
	composeType = el.getAttribute("gtdComposeType");
	this.selectTab(composeType, el);
};

ComposeUI.prototype.selectTab = function(composeType, el){

try{
	if( !el ) el = this._getTabElement(composeType);
	if( el ){
		if( this._lastTab ) GIPROTOTYPE.removeClassName(this._getTabElement(this._lastTab), "selected");
		GIPROTOTYPE.addClassName(el, "selected");
		this._lastTab = composeType;
	}
	
	var elTable = this._gtdinboxPage.gmailDOM.element("compose-table");
	if( elTable ){
		var elRows = elTable.getElementsByTagName("TR");
		
		var elTo = this._gtdinboxPage.gmailDOM.element("compose-to");
		
		switch( composeType ){
			case "compose-mail":	// show from/to
				for( var i = 1; i <= 5; i++ ){
					if( this._rowsState && this._rowsState[i] ) elRows[i].style.display = "";
				}
				if( this._lastTo!=null ) elTo.value = this._lastTo;
				break;
			case "compose-personal":	// hide from/to
				this._rowsState = [];
				for( var i = 1; i <= 5; i++ ){
					this._rowsState[i] = !(elRows[i].style.display=="none");
					elRows[i].style.display = "none";
				}
				this._lastTo = elTo.value;
				elTo.value = this._gtdinboxPage._environment.email;
				break;
		}
	}
		
}catch(e){
	if( GTDDEBUGMODE ) alert("composeui selectTab\n" + e.toString());
}	
};

ComposeUI.prototype._getTabElement = function(name){
	var result = this._doc.evaluate("//div[@id='" + this._id + name + "']", this._gtdinboxPage.gmailDOM.element("document"), null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
	return result.singleNodeValue;
};

ComposeUI.prototype.toggleLabel = function(e, label){
try{
	var elBody = null;
	var w = this._gtdinboxPage.window.frames[1];
	for( var i = 0; i < w.frames.length; i++ ){
		if( w.frames[i].document.body.className.indexOf("editable")>-1 ){
			elBody = w.frames[i].document.body;
			break;
		}
	}
	
	
	var selected = this._labelSelect.selected();
	
	var found = false;
	for( var i = 0; i < selected.length; i++ ){
		if( selected[i]==label.labelname ){
			selected.splice(i,1);
			found = true;
			break;
		}
	}
	if( !found ) selected.push(label.labelname);

	var elPlainText = this._gtdinboxPage.gmailDOM.element("plain-textarea");

	if( elBody ){
		var html = elBody.innerHTML;
		html = html.replace(/----------------------.{1,20}GTDInbox.+$/, "");
		
		if( selected.length > 0 ){
			html += "----------------------<br/>GTDInbox.com: Better Email &amp; Task Management for Gmail<br/>";	// TODO language
			html += "[" + selected.join("] [") + "]";
		}
		elBody.innerHTML = html;
	}
	if( elPlainText ){
		var html = elPlainText.value;
		html = html.replace(/----------------------(.|\r|\n|\t|\e|\f|\a|\v){1,20}GTDInbox(.|\r|\n|\t|\e|\f|\a|\v)+$/, "");
		
		if( selected.length > 0 ){
			html += "----------------------\nGTDInbox.com: Better Email & Task Management for Gmail\n";	// TODO language
			html += "[" + selected.join("] [") + "]";
		}
		elPlainText.value = html;	
	}
	
	this._labelSelect.selected(selected);
}catch(e){
	if( GTDDEBUGMODE ) alert("compose ui toggleLabel\n" + e.toString());
}
};

ComposeUI.prototype.destroy = function(){
	if( this._labelSelect ) this._labelSelect.destroy();
	if( this._showHiderLabels) this._showHiderLabels.destroy();

	this._eventObservers.destroy();
	
	this._tabs = null;
	this._labels = null;
	this._doc = null;
	this._gtdinboxPage = null;
};